package com.hxtec.polaris.commons.tasks;

import com.hxtec.polaris.commons.constant.GlobalVar;
import com.hxtec.polaris.commons.exception.MyException;
import com.hxtec.polaris.entity.ShopOrder;
import com.hxtec.polaris.mapper.ShopOrderMapper;
import com.hxtec.polaris.service.OrderManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Describtion 订单相关的任务
 * @Author yonyong
 * @Date 2019/12/16 15:23
 * @Version 1.0.0
 **/
@Component
@Transactional
public class OrderTask {

    private static final Logger logger = LoggerFactory.getLogger(OrderTask.class);

    @Resource
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    OrderManagerService orderManagerService;

    /**
     * 订单自动完成 针对已确认收货的订单/待评价订单 每日0点执行
     */
    @Scheduled(cron = "${mytask.day}")
    public void completeOrder(){
        logger.info("订单自动完成start");
        logger.info("订单自动完成end");
    }

    /**
     * 订单自动确认已收货
     */
    @Scheduled(cron = "${mytask.day}")
    public void confirmReceive(){
        logger.info("订单自动确认收货start");
        logger.info("订单自动确认收货end");
    }

    /**
     * 订单自动关闭   每小时检查一次
     */
    @Scheduled(cron = "${mytask.hour}")
    public void autoCloseOrder(){
        logger.info("订单自动关闭任务开始");
        try{
            doAutoCloseOrder();
        }catch (Exception e){
            throw new MyException("自动关闭失败");
        }
        logger.info("订单自动关闭任务结束");
    }

    /**
     * 执行订单自动关闭
     */
    private void doAutoCloseOrder() {
        List<ShopOrder> list = shopOrderMapper.selectDoAutoCloseOrder();
        for (ShopOrder shopOrder:list) {
            //添加操作记录
            orderManagerService.addOrderRecord(shopOrder.getId(), GlobalVar.OPERATER_AUTO,GlobalVar.ORDER_CLOSED,"系统自动关闭订单");
        }
        int affectrows = shopOrderMapper.doAutoCloseOrder(new Date());
        logger.info("本次自动关闭订单数:"+affectrows+"条");
    }
}
